import 'dart:io';
import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_enjoy_plus/api/user.dart';
import 'package:flutter_enjoy_plus/utils/EventBus.dart';
import 'package:flutter_enjoy_plus/utils/Toast.dart';
import 'package:image_picker/image_picker.dart';

class ProfilePage extends StatefulWidget {
  const ProfilePage({super.key, required this.userInfo});

  final Map<String, dynamic> userInfo;

  @override
  State<ProfilePage> createState() => _ProfilePageState();
}

class _ProfilePageState extends State<ProfilePage> {
  final TextEditingController _nickNameController = TextEditingController();

  // 是否正在上传用户信息
  bool _isUploading = false;
  // 是否选择了图片
  bool _isSelectedImage = false;
  // 文件名称
  String _fileName = '';

  // 选择图片
  _selectImage() async {
    // 1. 创建一个ImagePicker实例对象
    ImagePicker picker = ImagePicker();
    // 2. 调用pickImage方法，gallery: 相册，camera: 相机
    final XFile? image = await picker.pickImage(source: ImageSource.gallery);
    if (image != null) {
      // PromptAction.showToast('选择图片成功');
      // 已选择图片
      _isSelectedImage = true;
      // 获取文件名
      _fileName = image.name;
      // 更新头像
      setState(() {
        widget.userInfo["avatar"] = image.path;
      });
      // 关闭弹窗
      Navigator.pop(context);
    }
  }

  // 保存用户信息
  void _saveUserInfo() async {
    if (_nickNameController.text.isEmpty) {
      PromptAction.showErrorToast("昵称不能为空");
      return;
    }
    RegExp reg = RegExp(r'^[\u4e00-\u9fa5a-zA-Z0-9_]{2,18}$');
    if (!reg.hasMatch(_nickNameController.text)) {
      PromptAction.showErrorToast("不符合允许中文、字母、数字和下划线，长度2-18字符");
      return;
    }

    if (!_isUploading) {
      // 此时可以上传
      _isUploading = true;
      if (_isSelectedImage) {
        // 只有选择了图片才上传
        // 图片/视频上传需要转化为二进制数据  将本地路径转化为二进制
        // 将blob路径转化为字节数组方式：
        // 基于map对象 -> 转成formdata对象
        FormData data = FormData.fromMap({
          // file需要上传的二进制数据 -> 已知有blob临时地址
          // fromBytes -> 生成二进制数据

          // 旧版本 (windows目前不清楚) -> 针对于鸿蒙和web端 单独生成file
          // web端 MultipartFile.fromBytes
          // 鸿蒙端 MultipartFile.fromFileSync
          // 如何做: 需要判断设备环境
          // web KisWeb
          // android / ohos / ios  -> Platform.isAndroid
          // react-native / uniapp / flutter (痛点不是业务 -> 多端适配)
          // MultipartFile.fromFileSync(widget.userInfo['avatar'])
          "file": kIsWeb
              ? MultipartFile.fromBytes(
                  await XFile(widget.userInfo["avatar"]).readAsBytes(),
                  filename: _fileName,
                  contentType: DioMediaType("image", "png"))
              : MultipartFile.fromFileSync(widget.userInfo["avatar"]),
          "type": "avatar"
        });

        var res = await uploadFileAPI(data);
        setState(() {
          widget.userInfo["avatar"] = res["url"];
        });
        _isSelectedImage = false;
        _fileName = '';
      }

      // 保存昵称
      await updateUserInfoAPI({
        "nickName": _nickNameController.text,
        "avatar": widget.userInfo["avatar"] // 头像地址没有变化
      });
      _isUploading = false;
      PromptAction.showSuccessToast("修改成功");
      eventBus.fire(loginEvent()); // 不用返回 因为可能只是改了头像
    } else {
      PromptAction.showErrorToast("正在上传，请稍后");
    }
  }

  // 获取头像部件
  Widget getAvatar() {
    if (widget.userInfo["avatar"] != null && widget.userInfo["avatar"] != "") {
      // web端 文件地址是以 1. http/https 2. blob开头
      // 鸿蒙端 获取到的头像地址是以/data开头的，network无法解析
      // 可以通过判断+Image.file+File() 解决
      if (widget.userInfo["avatar"].startsWith("/data")) {
        return Image.file(
          File(widget.userInfo["avatar"]),
          width: 30,
          height: 30,
        );
      }
      return Image.network(
        widget.userInfo["avatar"],
        width: 30,
        height: 30,
      );
    }
    return Image.asset(
      'assets/images/avatar_1.jpg',
      width: 30,
      height: 30,
    );
  }

  // 显示选择头像弹层
  void _showAvatarDialog() {
    showModalBottomSheet(
        context: context,
        builder: (context) {
          return SizedBox(
            width: double.infinity,
            height: 180,
            child: Column(
              children: [
                Container(
                  alignment: Alignment.center,
                  height: 60,
                  decoration: const BoxDecoration(
                      border: Border(
                          bottom: BorderSide(width: 0.5, color: Colors.grey))),
                  child: const Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Icon(Icons.camera_alt),
                      SizedBox(
                        width: 10,
                      ),
                      Text(
                        "拍照",
                        style: TextStyle(fontSize: 20),
                      )
                    ],
                  ),
                ),
                Container(
                  alignment: Alignment.center,
                  height: 60,
                  decoration: const BoxDecoration(
                      border: Border(
                          bottom: BorderSide(width: 0.5, color: Colors.grey))),
                  child: GestureDetector(
                    // 默认手势组件中的子元素如果有留白区，则点击不到
                    // opaque 表示该组件会拦截命中测试，即使点击区域实际上并没有被绘制内容占据，也认为点击发生在该组件上
                    behavior: HitTestBehavior.opaque,
                    onTap: () {
                      _selectImage();
                    },
                    child: const Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Icon(Icons.photo_album),
                        SizedBox(
                          width: 10,
                        ),
                        Text(
                          "相册",
                          style: TextStyle(fontSize: 20),
                        )
                      ],
                    ),
                  ),
                ),
                Container(
                  alignment: Alignment.center,
                  height: 60,
                  child: GestureDetector(
                    behavior: HitTestBehavior.opaque,
                    onTap: () {
                      Navigator.pop(context);
                    },
                    child: const Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Icon(Icons.cancel_outlined),
                        SizedBox(
                          width: 10,
                        ),
                        Text(
                          "取消",
                          style: TextStyle(fontSize: 20),
                        )
                      ],
                    ),
                  ),
                )
              ],
            ),
          );
        });
  }

  @override
  void initState() {
    super.initState();
    if (widget.userInfo["nickName"] != null &&
        widget.userInfo["nickName"] != '') {
      _nickNameController.text = widget.userInfo["nickName"];
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        title: const Text('个人信息'),
        backgroundColor: Colors.transparent,
        centerTitle: true,
      ),
      body: ListView(
        padding: const EdgeInsets.all(10),
        children: [
          SizedBox(
            height: 40,
            child: Row(
              children: [
                const Text(
                  '头像',
                  style: TextStyle(fontSize: 16),
                ),
                const Spacer(),
                Row(
                  children: [
                    ClipRRect(
                      borderRadius: BorderRadius.circular(50.0),
                      child: GestureDetector(
                        onTap: () {
                          _showAvatarDialog();
                        },
                        child: getAvatar(),
                      ),
                    ),
                    const Icon(Icons.arrow_forward_ios, size: 12)
                  ],
                )
              ],
            ),
          ),
          Row(
            children: [
              const Text('昵称'),
              const Spacer(),
              Expanded(
                child: TextField(
                  controller: _nickNameController,
                  decoration: const InputDecoration(
                    hintText: '请输入昵称',
                    border: InputBorder.none,
                  ),
                  textAlign: TextAlign.right,
                ),
              ),
              const Icon(Icons.arrow_forward_ios, size: 12)
            ],
          ),
          const SizedBox(
            height: 20,
          ),
          Row(
            children: [
              Expanded(
                child: ElevatedButton(
                  style: ElevatedButton.styleFrom(
                    backgroundColor: const Color.fromARGB(255, 85, 145, 175),
                    minimumSize: const Size(100, 50),
                  ),
                  onPressed: () {
                    _saveUserInfo();
                  },
                  child: const Text(
                    '保存',
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 20,
                    ),
                  ),
                ),
              )
            ],
          )
        ],
      ),
    );
  }
}
